package com.link.play.fit.ai.ui.main.foodDatabase

import android.app.Activity
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.link.play.fit.ai.R
import com.link.play.fit.ai.bean.FoodInfoBean
import java.io.BufferedReader
import java.io.InputStreamReader
import java.io.Serializable
import java.lang.reflect.Type
import java.util.LinkedList


fun readJson(context: Activity): String {
    val string = StringBuilder()
    val inputStream = context.resources.openRawResource(R.raw.fooddata)
    inputStream?.let {
        val bfread = BufferedReader(InputStreamReader(inputStream))
        var line: String? = bfread.readLine()
        while (line != null) {
            string.append(line)
            line = bfread.readLine()
        }
    }
    return string.toString()
}

fun build(context:Activity): MutableList<FoodInfoBean>{
    val json = readJson(context)
    val result = Gson().fromJson(json, Array<FoodInfoBean>::class.java)
    return  result.toMutableList()
}

fun Serializable.toJson(): String {
    return Gson().toJson(this)
}

fun toListJson(list: List<FoodInfoBean>): String? {
    val listType: Type? = object : TypeToken<List<FoodInfoBean>?>() {}.getType()
    val gson = Gson()
    val json: String? = gson.toJson(list, listType)
    return json
}
